package cn.samler.shopapi.Service.impl;

import cn.samler.shopapi.Model.Response.User.Info;
import cn.samler.shopapi.Model.Sys.ServiceResult;
import cn.samler.shopapi.Mapper.UserMapper;
import cn.samler.shopapi.Entity.User;
import cn.samler.shopapi.Service.UserService;
import cn.samler.shopapi.Utils.BmobSMSUtils;
import cn.samler.shopapi.Utils.JWTUtil;
import cn.samler.shopapi.Utils.PasswordUtils;
import cn.samler.shopapi.Utils.TencentCaptchaUtils;
import org.springframework.stereotype.Service;


@Service
public class UserServiceImpl implements UserService {
    private final UserMapper userMapper;

    UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public int sendSms(String username, String ticket, String randStr, String userIp) {
        TencentCaptchaUtils tencentCaptchaUtils = TencentCaptchaUtils.getInstance();
        if (tencentCaptchaUtils.verify(ticket, randStr, userIp)) {
            BmobSMSUtils bmob = BmobSMSUtils.getInstance();

            if (bmob.send(username))
                return 0;
            return 1;
        }

        return 2;
    }

    @Override
    public ServiceResult loginForVerifyCode(String username, String vCode) {
        BmobSMSUtils bmob = BmobSMSUtils.getInstance();

        if (bmob.verify(username, vCode)) {
            User user = userMapper.findByUsername(username);
            if (user == null) {
                user = new User();
                user.setUsername(username);
                user.setPassword(PasswordUtils.getSHA256(PasswordUtils.getRandPassword()));

                userMapper.insertUser(user);
            }

            return ServiceResult.success(user);
        }

        return ServiceResult.failure(null);
    }

    @Override
    public ServiceResult loginForPassword(String username, String password) {
        User user = userMapper.loginTo(username, PasswordUtils.getSHA256(password));
        if (user != null) {
            return ServiceResult.success(user);
        }

        return ServiceResult.failure(null);
    }

    @Override
    public User findById(int id) {
        return userMapper.findById(id);
    }

    @Override
    public boolean setPassword(User user, String password) {
        if (password == null) return false;

        userMapper.setPassword(user.getId(), PasswordUtils.getSHA256(password));
        return true;
    }

    @Override
    public String createToken(User user) {
        return JWTUtil.getInstance().sign(user.getPayload());
    }

    @Override
    public void updateAvatar(User user, String url) {
        userMapper.updateAvatar(user.getId(), url);
    }

    @Override
    public Info getInfo(User user) {
        User item = userMapper.findById(user.getId());
        Info info = userMapper.getInfo(user.getId());
        info.setUser(item);

        return info;
    }
}
